package net.xju3_4.service.impl;

import net.xju3_4.common.utils.DateUtils;
import net.xju3_4.common.utils.PageInfo;
import net.xju3_4.dao.RentalDao;
import net.xju3_4.entity.Car;
import net.xju3_4.entity.OrderEntity;
import net.xju3_4.service.CarService;
import net.xju3_4.service.RentalService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 租车服务实现类
 */
public class RentalServiceImpl implements RentalService {

    private RentalDao rentalDao = new RentalDao();
    private CarService carService = new CarServiceImpl();

    // 订单状态常量（与数据库表结构匹配）
    private static final int STATUS_PENDING_PICKUP = 0;    // 待取车
    private static final int STATUS_RENTED = 2;            // 已取车
    private static final int STATUS_RETURNED = 3;          // 已还车
    private static final int STATUS_PENDING_PAYMENT = 4;   // 待支付
    private static final int STATUS_COMPLETED = 5;         // 订单完成
    private static final int STATUS_CANCELLED = -1;        // 已取消（自定义）

    @Override
    public OrderEntity createRental(Map<String, Object> rentalData) {
        try {
            Integer userId = Integer.parseInt(rentalData.get("userId").toString());
            String carId = (String) rentalData.get("carId");
            String startDate = (String) rentalData.get("startDate");
            String endDate = (String) rentalData.get("endDate");
            String dailyRentStr = (String) rentalData.get("dailyRent");

            // 检查车辆是否可租
            if (!isCarAvailable(carId, startDate, endDate)) {
                return null;
            }

            // 获取车辆信息，包括商家ID
            Car car = carService.selectOne(Integer.parseInt(carId));
            if (car == null) {
                return null; // 车辆不存在
            }

            // 计算租车费用
            double dailyRent = Double.parseDouble(dailyRentStr);
            Map<String, Object> costInfo = calculateRentalCost(startDate, endDate, dailyRent);

            // 创建订单实体
            OrderEntity rental = new OrderEntity();
            rental.setUserId(userId);
            rental.setCarId(carId);
            rental.setMerchantId(String.valueOf(car.getMerchantId())); // 设置商家ID
            rental.setStartTime(DateUtils.parseStr2Date(startDate));
            rental.setEndTime(DateUtils.parseStr2Date(endDate));
            rental.setRentDays(String.valueOf(costInfo.get("days")));
            rental.setDailyRent(dailyRentStr);
            rental.setEstimatedTotalAmount(String.valueOf(costInfo.get("totalAmount")));
            rental.setStatus(STATUS_PENDING_PAYMENT);

            // 保存到数据库
            boolean success = rentalDao.insertRental(rental);

            return success ? rental : null;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public PageInfo<OrderEntity> getUserRentals(String userId, String status, int pageNum, int pageSize) {
        try {
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;

            // 查询数据
            List<OrderEntity> rentals = rentalDao.selectUserRentals(userId, status, offset, pageSize);

            // 查询总数
            int total = rentalDao.countUserRentals(userId, status);

            // 构建分页信息
            PageInfo<OrderEntity> pageInfo = new PageInfo<>(pageNum, pageSize, total, rentals);

            return pageInfo;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public OrderEntity getRentalDetail(int rentalId, String userId) {
        try {
            // 将 String 类型的 userId 转换为 int 类型
            int userIdInt = Integer.parseInt(userId);
            return rentalDao.selectRentalDetail(rentalId, userIdInt);
        } catch (NumberFormatException e) {
            System.out.println("DEBUG: userId 转换失败: " + userId + " - " + e.getMessage());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean cancelRental(int rentalId, String userId, String reason) {
        try {
            // 获取订单详情
            OrderEntity rental = getRentalDetail(rentalId, userId);
            if (rental == null) {
                System.out.println("DEBUG: 订单不存在或无权限访问 - rentalId: " + rentalId + ", userId: " + userId);
                return false;
            }

            // 检查是否可以取消
            Integer currentStatus = rental.getStatus();
            System.out.println("DEBUG: 订单状态检查 - rentalId: " + rentalId + ", currentStatus: " + currentStatus + ", statusDescription: " + getStatusDescription(currentStatus));

            if (!canCancel(currentStatus)) {
                System.out.println("DEBUG: 订单状态不允许取消 - 只有待支付(4)和待取车(0)状态可以取消");
                return false;
            }

            // 更新状态为已取消
            boolean result = rentalDao.updateRentalStatus(rentalId, STATUS_CANCELLED, userId);
            System.out.println("DEBUG: 取消订单结果 - rentalId: " + rentalId + ", result: " + result);
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("DEBUG: 取消订单异常 - rentalId: " + rentalId + ", error: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean updateRentalStatus(int rentalId, Integer newStatus, String userId) {
        try {
            return rentalDao.updateRentalStatus(rentalId, newStatus, userId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Map<String, Object> calculateRentalCost(String startDate, String endDate, double dailyRent) {
        Map<String, Object> result = new HashMap<>();

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);

            // 计算天数
            long diffInMillies = Math.abs(end.getTime() - start.getTime());
            long days = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);

            // 至少租一天
            if (days == 0) {
                days = 1;
            }

            // 计算总费用
            double totalAmount = days * dailyRent;

            result.put("days", days);
            result.put("dailyRent", dailyRent);
            result.put("totalAmount", totalAmount);
            result.put("startDate", startDate);
            result.put("endDate", endDate);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("error", "日期格式错误");
        }

        return result;
    }

    @Override
    public boolean isCarAvailable(String carId, String startDate, String endDate) {
        try {
            // 查询指定时间段内是否有冲突的订单
            int conflictCount = rentalDao.countConflictRentals(carId, startDate, endDate);
            return conflictCount == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public String getStatusDescription(Integer status) {
        if (status == null) {
            return "状态为空";
        }

        switch (status) {
            case STATUS_PENDING_PICKUP:
                return "待取车";
            case STATUS_RENTED:
                return "已取车";
            case STATUS_RETURNED:
                return "已还车";
            case STATUS_PENDING_PAYMENT:
                return "待支付";
            case STATUS_COMPLETED:
                return "订单完成";
            case STATUS_CANCELLED:
                return "已取消";
            default:
                return "未知状态";
        }
    }

    /**
     * 检查订单是否可以取消
     */
    private boolean canCancel(Integer status) {
        if (status == null) {
            return false;
        }
        return status == STATUS_PENDING_PAYMENT || status == STATUS_PENDING_PICKUP;
    }
}
